"""
Problem 34: https://projecteuler.net/problem=34

145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: As 1! = 1 and 2! = 2 are not sums they are not included.
"""

# _*_ conding:UTF-8 _*_
'''
@author = Kuperain
@email = kuperain@aliyun.com
@IDE = VSCODE Python3.8.3
@creat_time = 2022/5/12
'''




from math import factorial
def solution() -> int:
    '''
    (d0,d1,d2,...,d_n-1) = SUM(di!)

        # n >= 2
        # 10^(n-1) < n * 9!  =>  n <= 8
    '''

    factors = {'0': 1, '1': 1}
    for i in range(2, 10):
        factors[str(i)] = factors[str(i-1)]*i

    # print(factors)

    nMax = 2

    while 10**(nMax-1) < nMax * factors["9"]:
        nMax += 1
    print(f'max(n) = {nMax-1}')

    res = []

    for num in range(10**2, 10**(nMax-1)):
        if num == sum([factors[x] for x in str(num)]):
            res.append(num)

    return sum(res)


if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=False)

    print(solution())
    # max(n) = 7
    # 145 40585
    # 40730
